package com.bjfu.service.impl;

import com.bjfu.dto.*;
import com.bjfu.mapper.*;
import com.bjfu.model.*;
import com.bjfu.mapper.AchievementMapper;
import com.bjfu.mapper.TeamMapper;
import com.bjfu.mapper.UserInfoMapper;
import com.bjfu.mapper.UserMapper;
import com.bjfu.model.Achievement;
import com.bjfu.model.Team;
import com.bjfu.model.User;
import com.bjfu.model.UserInfo;
import com.bjfu.model.Question;
import com.bjfu.service.TeamAdminService;
import com.bjfu.utils.Result;
import com.bjfu.utils.ResultCodeEnum;
import org.apache.ibatis.plugin.Interceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Random;

@Service
public class TeamAdminServiceImpl implements TeamAdminService {
    @Autowired
    private TeamMapper teamAdminMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserInfoMapper userInfoMapper;
    @Autowired
    private ErrorInfoMapper errorInfoMapper;
    @Autowired
    private AchievementMapper achievementMapper;
    @Autowired
    private ArticleMapper articleMapper;

    @Autowired
    private QuestionMapper questionMapper;

    @Autowired
    private JavaMailSender mailSender;  // 注入邮件发送服务



    @Override
    public Result updateTeamInfo(TeamDTO team) {
        if(team.getTeam_id()!=1){
            return Result.build(null,ResultCodeEnum.TEAM_NOT_FOUND);
        }
        Team update_team=new Team();
        update_team.setAdminId(team.getAdmin_id());
        update_team.setTeamId(team.getTeam_id());
        update_team.setName(team.getName());
        update_team.setDescription(team.getDescription());
        update_team.setResearchField(team.getResearch_field());
        update_team.setCreatedTime(team.getCreated_time());
        int result = teamAdminMapper.updateTeam(update_team);
        if (result > 0) {
            return Result.ok(update_team);
        } else {
            return Result.build(null, ResultCodeEnum.UPDATE_FAILED);
        }
    }

    @Override
    public Result addMember(MemberRequestDTO memberRequestDTO) {
        //引用通用接口的注册逻辑
        /*// 1. 校验用户名称是否已存在
        User existingUser = userMapper.getUserByUsername(memberRequestDTO.getUsername());
        if (existingUser != null) {
            return Result.build(null, ResultCodeEnum.USER_EXISTS);
        }*///可重名
        System.out.println(memberRequestDTO);
        // 2. 创建团队成员
        User user = new User();
        user.setUsername(memberRequestDTO.getUsername());
        user.setPassword(memberRequestDTO.getPassword());
        user.setRole(2); // 团队成员2,普通用户3
        user.setStatus(1); // 唯一的区别：无需审核 ！！初始状态为待审核
        user.setRegistrationTime(LocalDateTime.now());
        System.out.println(user);
        // 插入用户
        int rowsInserted = userMapper.insertUser(user);
        if (rowsInserted <= 0) {
            return Result.build(null, ResultCodeEnum.INSERT_FAILED);
        }

        // 3. 创建用户详细信息
        UserInfo userInfo = new UserInfo();
        userInfo.setUserId(user.getUserId());
        userInfo.setName(memberRequestDTO.getName()); // 姓名可以与用户名相同
        userInfo.setApplyReason("用户管理员添加");//不允许为空，否则报错
        userInfo.setStatus(2); // 注意改了    改为已经审核 ！！初始状态为待审核
        userInfo.setTeamId(1L);//只有一个团队
        //当审核通过时，既要更新user状态，也要更新user_info的状态。
        userInfo.setAvatarUrl(memberRequestDTO.getAvatar_url());
        userInfo.setResearchField(memberRequestDTO.getResearch_field());
        userInfo.setEmail(memberRequestDTO.getEmail());
        // 插入用户详细信息
        int infoInserted = userInfoMapper.insertUserInfo(userInfo);
        if (infoInserted <= 0) {
            return Result.build(null, ResultCodeEnum.INSERT_FAILED);
        }

        // 4. 返回成功
        return Result.ok(user);
    }

    //个人信息有团队成员、团队管理员、普通用户三种role的
    //团队管理员的信息：由超级管理员直接编辑更新，因此他的个人信息状态一定为2，已审核
    //团队成员的个人信息：可以是自己注册得到，此时注册账号时还未经过审核时，个人信息状态为1；（若团队管理员审核账号通过，则个人信息变为2）
    // 也可以是自己更新，此时状态已经激活，但是个人信息修改，所以个人信息状态为1（这是需要团队管理员审核的，只有这种状态是需要审核个人信息的）
    //也可以是管理员直接新增并且提交个人信息，那么个人信息视为已审核2
    //普通成员的个人信息由注册时提交，此时为1，当管理员审核账号状态时，若通过则个人信息也变为已审核2（这是不可以自己更新的）
    //也就是 状态为1的只有两种情况，未被激活的团队成员或者普通用户或者激活了但是更新了个人信息的团队成员（现在对后者操作只需要排除已激活的）
    @Override
    public Result queryPendingMembers() {
        List<UserInfo> userInfos = userInfoMapper.queryPendingMembers();
        // 如果待审核的成员信息列表为空，返回错误
        if (userInfos == null || userInfos.isEmpty()) {
            return Result.build(null,ResultCodeEnum.USER_NOT_FOUND);  // 返回错误消息
        }

        // 遍历并筛选出符合条件的成员
        userInfos.removeIf(userInfo -> {
            Long userId = userInfo.getUserId();
            Integer status = userMapper.getUserById(userId).getStatus();
            return status != 1;  // 如果 status 不是 1，则移除该成员
        });
        return Result.ok(userInfos);
    }

    //获取全部成果信息
    @Override
    public Result getAchievements() {
        // 获取所有状态的成果
        List<Achievement> achievements = achievementMapper.getAchievements(); // 查询方法需支持获取所有状态的成果

        // 判断查询结果是否为空
        if (achievements != null && !achievements.isEmpty()) {
            return Result.ok(achievements);  // 如果有结果，返回成功的结果
        } else {
            return Result.build(null, ResultCodeEnum.ACHIEVEMENT_NOT_FOUND);  // 如果没有结果，返回“未找到成果”错误信息
        }
    }
    @Override
    public Result getArticles() {
        // 从获取所有状态的文章
        List<Article> articles = articleMapper.getALLArticles(); // 查询方法需支持获取所有状态的文章

        // 判断查询结果是否为空
        if (articles != null && !articles.isEmpty()) {
            return Result.ok(articles); // 如果有结果，返回成功的结果
        } else {
            return Result.build(null, ResultCodeEnum.ARTICLE_NOT_FOUND); // 如果没有结果，返回“未找到文章”错误信息
        }
    }


    @Override
    public Result getAchievement(Integer category) {
        // 使用achievementMapper查询指定类别的成果
        List<Achievement> achievements = achievementMapper.getAchievement(category);

        // 判断是否查询到数据
        if (achievements == null || achievements.isEmpty()) {
            return Result.build(null, ResultCodeEnum.ACHIEVEMENT_NOT_FOUND);
        }

        // 返回查询结果
        return Result.ok(achievements);
    }

    @Override
    public Result getNotOpenAchievements() {
        // 获取所有不公开状态的成果
        List<Achievement> achievements = achievementMapper.getNotOpenAchievements(); // 查询方法需支持获取所有不公开状态的成果

        // 判断查询结果是否为空
        if (achievements != null && !achievements.isEmpty()) {
            return Result.ok(achievements);  // 如果有结果，返回成功的结果
        } else {
            return Result.build(null, ResultCodeEnum.ACHIEVEMENT_NOT_FOUND);  // 如果没有结果，返回“未找到成果”错误信息
        }
    }

    @Override
    public Result getNotOpenAchievement(Integer category) {
        // 使用achievementMapper查询指定类别的成果
        List<Achievement> achievements = achievementMapper.getNotOpenAchievement(category);

        // 判断是否查询到数据
        if (achievements == null || achievements.isEmpty()) {
            return Result.build(null, ResultCodeEnum.ACHIEVEMENT_NOT_FOUND);
        }

        // 返回查询结果
        return Result.ok(achievements);
    }


    @Override
    public Result judgeTeamMemberInfo(JudgeRequest judgeRequest) {
        System.out.println(judgeRequest);
        // 调用Mapper方法审核团队成员
        int result = userInfoMapper.judgeTeamMemberInfo(judgeRequest.getUser_id(), judgeRequest.getPass_status() ? 2 : 3);

        if (result > 0) {
            if (judgeRequest.getPass_status()) {
                // 如果审核通过，返回审核通过的结果
                return Result.ok(judgeRequest);
            } else {
                // 如果审核不通过，写入拒绝理由
                //首先验证是否具有该type和type_id，若有则直接覆盖。
                List<ErrorInfo>errorInfos=errorInfoMapper.getErrorInfoByTypeIdAndType(judgeRequest.getUser_id(),4);
                if(errorInfos!=null&&!errorInfos.isEmpty()){
                    String cause=judgeRequest.getRefuse_cause();
                    Long errorId=errorInfos.get(0).getId();
                    errorInfoMapper.updateErrorInfoCause(cause, errorId);
                }
                else {
                    ErrorInfo errorInfo = new ErrorInfo();
                    errorInfo.setType(4);  // 不通过类型为团队成员的简介4！！若为成员账号则为3
                    errorInfo.setTypeId(judgeRequest.getUser_id());
                    errorInfo.setCause(judgeRequest.getRefuse_cause());
                    errorInfoMapper.insertErrorInfo(errorInfo);
                }
                return Result.build(judgeRequest, ResultCodeEnum.JUDGE_REFUSED);  // 返回拒绝结果
            }
        } else {
            // 更新失败
            return Result.build(null, ResultCodeEnum.UPDATE_FAILED);
        }
    }

    @Override
    public Result addAchievement(AchievementDTO achievementDTO) {
        Achievement achievement=new Achievement();
        achievement.setCategory(achievementDTO.getCategory());
        achievement.setTitle(achievementDTO.getTitle());
        achievement.setSummary(achievementDTO.getSummary());
        achievement.setDescription(achievementDTO.getDescription());
        achievement.setContent(achievementDTO.getContent());
        achievement.setAttachmentLink(achievementDTO.getAttachment_link());
        achievement.setCreatedTime(achievementDTO.getCreated_time());
        achievement.setStatus(1);//保存并且待审核
        achievement.setTeamId(1L);
        System.out.println(achievement);
        int result=achievementMapper.insertAchievement(achievement);
        if(result>0){return Result.ok(achievement);}
        else{return Result.build(null,ResultCodeEnum.INSERT_FAILED);}
    }

    @Override
    public Result addArticle(ArticleDTO articleDTO) {
        // 创建 Article 实体
        Article article = new Article();
        article.setCategory(articleDTO.getCategory());
        article.setTitle(articleDTO.getTitle());
        article.setSummary(articleDTO.getSummary());
        article.setContent(articleDTO.getContent());
        article.setAttachmentLink(articleDTO.getAttachment_link());
        article.setPublishDate(articleDTO.getPublish_date());
        article.setStatus(1); // 假设新文章为待审核状态
        article.setTeamId(1L); // 假设属于某个固定团队，实际值可根据需求调整

        // 打印日志，检查实体内容
        System.out.println(article);

        // 插入文章到数据库
        int result = articleMapper.insertArticle(article);

        // 判断插入是否成功，并返回相应结果
        if (result > 0) {
            return Result.ok(article);
        } else {
            return Result.build(null, ResultCodeEnum.INSERT_FAILED);
        }
    }


    @Override
    public Result updateAchievement(AchievementDTO achievementDTO) {
        Achievement old_achievement=achievementMapper.getAchievementById(achievementDTO.getAchievement_id());
        if(old_achievement==null){
            return Result.build(null,ResultCodeEnum.ACHIEVEMENT_NOT_FOUND);
        }
        Achievement achievement=new Achievement();
        achievement.setAchievementId(achievementDTO.getAchievement_id());
        achievement.setCategory(achievementDTO.getCategory());
        achievement.setTitle(achievementDTO.getTitle());
        achievement.setSummary(achievementDTO.getSummary());
        achievement.setDescription(achievementDTO.getDescription());
        achievement.setContent(achievementDTO.getContent());
        achievement.setAttachmentLink(achievementDTO.getAttachment_link());
        achievement.setCreatedTime(achievementDTO.getCreated_time());
        achievement.setStatus(1);//保存并且待审核
        achievement.setTeamId(1L);
        System.out.println(achievement);
        int result=achievementMapper.updateAchievement(achievement);
        if(result>0){return Result.ok(achievement);}
        else{return Result.build(null,ResultCodeEnum.UPDATE_FAILED);}
    }
    @Override
    public Result updateArticle(ArticleDTO articleDTO) {
        // 检查文章是否存在
        if (articleMapper.getArticleById(articleDTO.getArticle_id()) == null) {
            return Result.build(null, ResultCodeEnum.ARTICLE_NOT_FOUND);
        }

        // 创建 Article 对象并设置属性
        Article article = new Article();
        article.setArticleId(articleDTO.getArticle_id());
        article.setTitle(articleDTO.getTitle());
        article.setCategory(articleDTO.getCategory());
        article.setSummary(articleDTO.getSummary());
        article.setContent(articleDTO.getContent());
        article.setAttachmentLink(articleDTO.getAttachment_link());
        article.setPublishDate(articleDTO.getPublish_date());
        article.setStatus(1); // 设置状态为待审核
        article.setTeamId(1L); // 假设团队ID为1L
        System.out.println(article);
        // 更新文章
        int result = articleMapper.updateArticle(article);

        // 判断更新结果
        if (result > 0) {
            return Result.ok(article);
        } else {
            return Result.build(null, ResultCodeEnum.UPDATE_FAILED);
        }
    }



    @Override
    public Result deleteAchievement(Long achivementId) {
        Achievement achievement= achievementMapper.getAchievementById(achivementId);
        int result=achievementMapper.deleteAchievement(achivementId);
        if(achievement==null){return Result.build(null,ResultCodeEnum.ACHIEVEMENT_NOT_FOUND);}
        if(result>0){return Result.ok(null);}
        else{return Result.build(null,ResultCodeEnum.DELETE_FAILED);}
    }
    //删除文章
    @Override
    public Result deleteArticle(Long article_id) {
        // 根据文章ID获取文章
        Article article = articleMapper.getArticleById(article_id);
        // 检查文章是否存在
        if (article == null) {
            return Result.build(null, ResultCodeEnum.ARTICLE_NOT_FOUND);
        }
        // 尝试删除文章
        int result = articleMapper.deleteArticle(article_id);
        // 判断删除是否成功
        if (result > 0) {
            return Result.ok(null);
        } else {
            return Result.build(null, ResultCodeEnum.DELETE_FAILED);
        }
    }



    @Override
    public Result getNeedCancelUsers() {
        /*// 调用 userInfoMapper 获取 status 为 4 的所有需要被注销的用户信息
        List<UserInfo> cancelledUsers = userInfoMapper.getUsersNeedCancel();

        // 判断查询结果是否为空
        if (cancelledUsers != null && !cancelledUsers.isEmpty()) {
            // 返回查询到的用户信息
            return Result.ok(cancelledUsers);
        } else {
            // 如果没有找到符合条件的用户，返回错误信息
            return Result.build(null, ResultCodeEnum.USER_NOT_FOUND);
        }*/
        // 查询role为2或3的已激活的用户信息
        List<UserWithInfo> cancelledUsers = userInfoMapper.getCouldcancelledUser();

        // 判断查询结果是否为空
        if (cancelledUsers != null && !cancelledUsers.isEmpty()) {
            // 返回查询到的用户信息
            return Result.ok(cancelledUsers);
        } else {
            // 如果没有找到符合条件的用户，返回错误信息
            return Result.build(null, ResultCodeEnum.USER_NOT_FOUND);
        }
    }

    @Override
    public Result getUserInfoByUserName(String username) {
        // 调用 userMapper 获取指定 name 的用户信息
        Long id  = userMapper.getMemberByName(username);
        // 如果查询结果为空，说明没有找到该成员
        if (id != null) {
            UserInfo member = userInfoMapper.getUserInfoById(id);
            // 返回成员信息
            return Result.ok(member);
        } else {
            // 如果没有找到成员，返回用户未找到的结果
            return Result.build(null, ResultCodeEnum.USER_NOT_FOUND);
        }
    }

    @Override
    public Result getUserInfoByEmail(String email) {
        // 调用UserInfoMapper的getUserInfoByEmail方法查询用户信息
        UserInfo userInfo = userInfoMapper.getUserInfoByEmail(email);

        // 判断是否查询到结果
        if (userInfo != null) {
            // 返回查询结果
            return Result.ok(userInfo);
        } else {
            // 如果没有找到用户信息，返回错误信息
            return Result.build(null, ResultCodeEnum.USER_NOT_FOUND);
        }
    }

    @Override
    public Result getWaitJudgeUsers() {
      /*  // 调用 userInfoMapper 获取 status 为 0和4 的所有需要被注销的用户信息
        List<UserInfo> cancelledUsers = userInfoMapper.getWaitJudgeUsers();

        // 判断查询结果是否为空
        if (cancelledUsers != null && !cancelledUsers.isEmpty()) {
            // 返回查询到的用户信息
            return Result.ok(cancelledUsers);
        } else {
            // 如果没有找到符合条件的用户，返回错误信息
            return Result.build(null, ResultCodeEnum.USER_NOT_FOUND);
        }*/
        /*List<UserInfo> cancelledUsers = userInfoMapper.getRegisteringUser();*/
        List<UserWithInfo> cancelledUsers = userInfoMapper.getRegisteringUserWithInfo();

        // 判断查询结果是否为空
        if (cancelledUsers != null && !cancelledUsers.isEmpty()) {
            // 返回查询到的用户信息
            return Result.ok(cancelledUsers);
        } else {
            // 如果没有找到符合条件的用户，返回错误信息
            return Result.build(null, ResultCodeEnum.USER_NOT_FOUND);
        }
    }

    @Override
    public Result getAllQuestions() {
        // 调用 questionMapper 获取所有问题

        List<Question> questions = questionMapper.getAllQuestions();

        // 判断查询结果是否为空
        if (questions != null && !questions.isEmpty()) {
            // 如果有结果，返回成功的结果
            return Result.ok(questions);
        } else {
            // 如果没有结果，返回“未找到问题”错误信息
            return Result.build(null, ResultCodeEnum.QUESTION_NOT_FOUND);
        }
    }

    @Override
    public Result getQuestionInfo(Long questionId) {
        // 调用 questionMapper 获取指定 questionId 的问题信息
        Question question = questionMapper.getQuestionById(questionId);

        // 如果查询结果为空，说明没有找到该问题
        if (question != null) {
            // 返回问题信息
            return Result.ok(question);
        } else {
            // 如果没有找到问题，返回问题未找到的结果
            return Result.build(null, ResultCodeEnum.QUESTION_NOT_FOUND);
        }
    }

    // 根据提问状态获取所有问题
    @Override
    public Result getAllQuestionsByStatus(Integer status) {
        // 调用 questionMapper 获取指定状态的所有问题
        List<Question> questions = questionMapper.getQuestionsByStatus(status);

        // 如果查询结果为空，说明没有符合条件的提问
        if (questions != null && !questions.isEmpty()) {
            // 返回符合条件的所有问题
            return Result.ok(questions);
        } else {
            // 如果没有找到符合条件的问题，返回“未找到提问”错误信息
            return Result.build(null, ResultCodeEnum.QUESTION_NOT_FOUND);
        }
    }

    //根据id获取权限permit
    @Override
    public Result getPermitByUserId(Long userId) {
        // 调用 userMapper 获取用户的权限值
        String permit = userMapper.getPermitByUserId(userId);

        // 如果查询结果为空，说明用户不存在或没有权限值
        if (permit != null) {
            // 返回权限值
            return Result.ok(permit);
        } else {
            // 如果没有找到权限，返回权限未找到的结果
            return Result.build(null, ResultCodeEnum.PERMISSION_NOT_FOUND);
        }
    }



    @Override
    public Result changeAchievementStatus(AchievementDTO achievementDTO) {
        Long achievement_id=achievementDTO.getAchievement_id();
        Achievement achievement=achievementMapper.getAchievementById(achievement_id);
        if(achievement==null){
            return Result.build(null,ResultCodeEnum.ACHIEVEMENT_NOT_FOUND);
        }
        if(achievement.getStatus()!=2&&achievement.getStatus()!=4){
            return Result.build(null,ResultCodeEnum.ACHIEVEMENT_STATUS_ERROR);
        }//若不属于已公开或者已隐藏的状态，则报错不允许进行操作
       achievement.setStatus(achievementDTO.getStatus());
       if(achievementMapper.changeAchievementStatus(achievement)>0){
           System.out.println(achievement);
           return Result.ok(achievement);
       }
        else{
            return Result.build(null,ResultCodeEnum.UPDATE_FAILED);
       }
    }

    @Override
    public Result shenheRegister(JudgeRequest judgeRequest) {
        if(userMapper.getUserById(judgeRequest.getUser_id()).getStatus()!=0){
            return Result.build(null,ResultCodeEnum.INSUFFICIENT_PERMISSIONS);//当前请求用户不是注册待审核状态
        }
        // 调用Mapper方法审核申请注册的团队成员和普通用户
        int result = userMapper.judgeMember(judgeRequest.getUser_id(), judgeRequest.getPass_status() ? 1 : 2);
        // 如果审核通过，返回审核通过的结果!注意，除了用户账号的状态需要更新，用户信息的状态也需要更新
        userInfoMapper.judgeTeamMemberInfo(judgeRequest.getUser_id(), judgeRequest.getPass_status()?2:3);
        if (result > 0) {
            if (judgeRequest.getPass_status()) {
                return Result.ok(judgeRequest);
            } /*else {
                // 如果审核不通过，写入拒绝理由
                ErrorInfo errorInfo = new ErrorInfo();
                errorInfo.setType(3);  // 成员账号则为3
                errorInfo.setTypeId(judgeRequest.getUser_id());
                errorInfo.setCause(judgeRequest.getRefuse_cause());
                errorInfoMapper.insertErrorInfo(errorInfo);*/
            else {
                // 如果审核不通过，写入拒绝理由
                //首先验证是否具有该type和type_id，若有则直接覆盖。
                List<ErrorInfo>errorInfos=errorInfoMapper.getErrorInfoByTypeIdAndType(judgeRequest.getUser_id(),3);
                if(errorInfos!=null&&!errorInfos.isEmpty()){
                    String cause=judgeRequest.getRefuse_cause();
                    Long errorId=errorInfos.get(0).getId();
                    errorInfoMapper.updateErrorInfoCause(cause, errorId);
                }
                else {
                    ErrorInfo errorInfo = new ErrorInfo();
                    errorInfo.setType(3);  // 不通过类型为团队成员的简介4！！若为成员账号则为3
                    errorInfo.setTypeId(judgeRequest.getUser_id());
                    errorInfo.setCause(judgeRequest.getRefuse_cause());
                    errorInfoMapper.insertErrorInfo(errorInfo);
                }
                return Result.build(judgeRequest, ResultCodeEnum.JUDGE_REFUSED);  // 返回拒绝结果
            }
        } else {
            // 更新失败
            return Result.build(null, ResultCodeEnum.UPDATE_FAILED);
        }
    }

    //注销用户
    @Override
    public Result cancelUser(Long user_id) {
        Integer user_status=3;//被注销status为3
        if(userMapper.getUserById(user_id)==null){
            return Result.build(null,ResultCodeEnum.USER_NOT_FOUND);//不存在该用户
        }
        int result=userMapper.judgeMember(user_id,user_status);
        if(result>0){
            Integer user_info_status=5;//user_info状态为5，表示当前用户已被注销，信息也是被注销状态
            userInfoMapper.judgeTeamMemberInfo(user_id,user_info_status);
            return Result.ok(userMapper.getUserById(user_id));
        }
        else{
            return Result.build(null,ResultCodeEnum.CANCELFAILED);//注销失败
        }
    }

    @Override
    public Result ResetPasswordByUserId(Long userId) {
        // 1. 查询用户信息
        User user = userMapper.getUserById(userId);
        if (user == null) {
            return Result.build(null,ResultCodeEnum.USER_NOT_FOUND);
        }

        // 2. 生成临时密码
        String tempPassword = generateTempPassword();

        // 3. 更新数据库中的密码
        boolean isUpdated = userMapper.updateUserPassword(userId, tempPassword);
        if (!isUpdated) {
            return Result.build(null,ResultCodeEnum.UPDATE_FAILED);
        }

        // 4. 发送临时密码至用户邮箱
        String email = userInfoMapper.getUserInfoById(userId).getEmail();
        boolean emailSent = sendTemporaryPasswordEmail(email, tempPassword);
        if (!emailSent) {
            return Result.build(null,ResultCodeEnum.SENDFAILED);
        }

        // 5. 返回成功结果
        return Result.ok("密码重置成功，临时密码已发送到用户邮箱，请尽快登录并修改密码");
    }
    // 生成临时密码
    private String generateTempPassword() {
        String characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder password = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 8; i++) {  // 假设生成8位的临时密码
            int index = random.nextInt(characters.length());
            password.append(characters.charAt(index));
        }
        return password.toString();
    }

    // 发送临时密码的邮件
    private boolean sendTemporaryPasswordEmail(String to, String tempPassword) {
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setTo(to);
            message.setSubject("您的临时密码");
            message.setText("您好！\n\n您的账户已重置密码，临时密码为: " + tempPassword + "\n请尽快登录并修改密码。");
            message.setFrom("15879604631@163.com");  // 发送者邮箱
            mailSender.send(message);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
    }
    //回复问题
    @Override
    public Result anwerQuestion(QuestionDTO questionDTO) {
        Long question_id = questionDTO.getQuestion_id();
        Question question = questionMapper.getQuestionById(question_id);
        if (question == null) {
            return Result.build(null, ResultCodeEnum.QUESTION_NOT_FOUND);
        }
        System.out.println(question);
        //status在Mapper设置为1已回答
        int result=questionMapper.answerQuestion(question_id, questionDTO.getReply_content(), LocalDateTime.now());
        if(result>0){return Result.ok(questionMapper.getQuestionById(question_id));}
        else{return Result.build(null,ResultCodeEnum.REPLY_ERROR);}
    }



    //标记提问状态（关闭提问）
    @Override
    public Result tagQuestion(QuestionDTO questionDTO) {
        System.out.println(questionDTO);
        if(questionMapper.getQuestionById(questionDTO.getQuestion_id())==null){
            return Result.build(null,ResultCodeEnum.QUESTION_NOT_FOUND);
        }
        int result=questionMapper.updateQuestionStatus(questionDTO.getQuestion_id(), questionDTO.getStatus());
        if(result>0){
            return Result.ok(questionMapper.getQuestionById(questionDTO.getQuestion_id()));
        }
        else{
            return Result.build(null,ResultCodeEnum.UPDATE_FAILED);
        }
    }

    @Override
    public Result getMemberAndUserInfo() {
        List<UserWithInfo>userWithInfos=userInfoMapper.getMemberAndUserInfo();
        if(userWithInfos==null||userWithInfos.isEmpty()){
            return Result.build(null,ResultCodeEnum.USER_NOT_FOUND);
        }
        else{
            return Result.ok(userWithInfos);
        }
    }
}
